﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Ionic.Utils.Zip;
using Rosetta.Default;

namespace Rosetta.AddIns.Compression
{
    public sealed class ZipFileConverter : Converter
    {
        #region Constructors

        public ZipFileConverter()
            : base("ZipFile Converter")
        {
            Category = "Compression";

            Add<ZipFile, IEnumerable<ZipEntry>>("GetAllEntries", GetAllEntries, "zip");
            Add<ZipFile, Regex, IEnumerable<ZipEntry>>("GetEntries", GetEntries, "zip", "filterRegex");
            Add<byte[], ZipFile>("Read", Read, "buffer");
        }

        #endregion

        #region Class Methods

        public static IEnumerable<ZipEntry> GetAllEntries([NotNull] ZipFile zip)
        {
            if (zip == null)
            {
                throw new ArgumentNullException("zip");
            }

            return zip;
        }

        public static IEnumerable<ZipEntry> GetEntries([NotNull] ZipFile zip, [NotNull] Regex filterRegex)
        {
            if (zip == null)
            {
                throw new ArgumentNullException("zip");
            }
            if (filterRegex == null)
            {
                throw new ArgumentNullException("filterRegex");
            }

            return zip.Where(entry => filterRegex.IsMatch(entry.FileName));
        }

        private static ZipFile Read([NotNull] byte[] buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            return ZipFile.Read(buffer);
        }

        #endregion
    }
}